package com.flexdms.i18n;

import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_SUPER;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V1_5;

import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;


public class MsgClassLoader extends ClassLoader
{

	List<Class<?>> clsz=new ArrayList<Class<?>>();
	
	
	 public MsgClassLoader(ClassLoader pClassLoader)
	{
		super(pClassLoader);
	}


	//only responsible for resource class loading
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		for(Class<?> cls: clsz)
		{
			if (cls.getName().equalsIgnoreCase(name))
			{
				return cls;
			}
		}
		return null;
     }

	

	@Override
	protected Class<?> loadClass(String name, boolean resolve)
			throws ClassNotFoundException
	{
		
		Class<?> cls=findClass(name);
		if (cls!=null)
		{
			return cls;
		}
		cls=super.loadClass(name, resolve);
		return cls;
	}

	 protected static final String INIT = "<init>";
	public void addClass(String column)
     {
    	 column=column.replace('-', '_');
    	 String localeString=column;

 		Class<?> parent=DefaultResourceImpl.class;
         String parentClassName = parent.getName();
         String className=DBMsgs.class.getName()+"_"+localeString;
         String classNameAsSlashes = className.replace('.', '/');
         String parentClassNameAsSlashes = parentClassName.replace('.', '/');

         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

         // public class Foo extends DynamicEntityImpl {
         cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, classNameAsSlashes, null, parentClassNameAsSlashes, null);
         
      // public Foo() {
         // super();
         // }
         MethodVisitor mv= cw.visitMethod(ACC_PUBLIC, INIT, "()V", null, null);
         mv.visitVarInsn(ALOAD, 0);
         mv.visitMethodInsn(INVOKESPECIAL, parentClassNameAsSlashes, INIT, "()V");
         mv.visitInsn(RETURN);
         mv.visitMaxs(0, 0);
         cw.visitEnd();
         byte[] bytes= cw.toByteArray();
         
         clsz.add(defineClass(className, bytes, 0, bytes.length));
     }
}
